import { addRecord, delRecord, findAllRecord } from '@renderer/apis/recordAPI'
import { ref } from 'vue'
import useProj from './useProj'
import useTeam from './useTeam'
import useComp from './useComp'

const { all: allTeam, add: addTeam, teams: lst_team } = useTeam()
const { all: allProj, add: addProj, projs: lst_proj } = useProj()
const { all: allComp, add: addComp, comps: lst_comp } = useComp()

export default () => {
  const records = ref<recordModel[]>()

  const read = async (log: logModel) => {
    let tableData: recordModel[] = []
    const content = log.content.replace(/\s/g, '')
    const data = content.match(/\d{4}年\d{1,2}月\d{1,2}日/gi)!
    // 重新梳理
    await allProj()
    await allTeam()
    await allComp()
    const reg = content.matchAll(/（\d{1,2}）(.{0,30}工程).{0,10}，(\D{2,4})，?(S\d{4}).{0,10}负责人(.{2,4})[,，]/gi)
    for await (const r of reg) {
      const [_, projName, compName, teamName, fzr] = r
      let p = lst_proj.value.find((p) => p.name.includes(projName))
      let c = lst_comp.value?.find((c) => c.name.includes(compName))
      let t = lst_team.value?.find((t) => t.team === teamName)

      if (!p)
        p = (await addProj({
          name: projName,
          shortName: projName,
          company: '',
          dianya: '110kV',
        })) as projModel

      if (!c)
        c = (await addComp({
          name: compName,
          shortName: compName,
          fr: '..',
          sjfzr: '..',
        })) as compModel

      if (!t)
        t = (await addTeam({
          compId: c?.id,
          team: teamName,
          fzr,
        })) as teamModel

      tableData.push({
        data: data[0],
        proj: p,
        team: t,
      })
    }
    return tableData
  }

  // 所有记录
  const all = async (args = {}) => {
    const { data } = (await findAllRecord(args)) as any
    records.value = data
  }

  // 新增
  const add = async (data: any) => {
    await addRecord(data)
  }

  // 删除
  const del = async (id: number) => {
    await delRecord(id)
  }

  return { read, add, all, del, records }
}
